안녕하세요?
자료를 원하시는 분들이 많아 수업 자료를(html 파일) 공유해 드립니다. 맨 마지막 치킨ㅋㅋ 엑셀파일은 실제 주소여서 따로 제공하지 않겠습니다. 다른 주소로 연습하시거나 개별적으로 만들어서 사용하시기 바랍니다. Google Maps API 용 Key는 간단한 정보(카드)만 입력하면 받으실 수 있습니다. 소소하게 교육용으로 조금 사용하는 것은 결재하지 않는 것으로 알고 있습니다. (추후 바뀌는 것은 스스로 체크하시기 바랍니다.) 아래 코드에는 개별적으로 제공받은 키를 넣으시면 됩니다.
짧은 시간 급히 준비한 내용이라 일부 효율적인 코딩이 아닐 수 있으니 참고해 주세요. 제 파일을 비롯하여 아카데미에서 배포된 모든 자료들은 참석한 분들에게만 공유된 자료입니다. 개인적인 교육용으로만 참고하시고 다른 분들께 전달하거나 절대로 다른 목적으로 사용하지 마시길 부탁드립니다. 부족한 준비에도 열심히 따라와 주셔서 감사합니다.^^ 많은 도움이 되었기를~~~
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.rc('font', family='Malgun Gothic')
df = pd.read_excel("data/2018_modified_data.xlsx")
df.head()
del df['도로조건']
del df['연도']
del df['월']
del df['DongLi']
df.head()
df['SiDo'].unique()
df['SiGunGu'].unique()
df['ID'].unique()
Seoul = df[df['SiDo']=='서울특별시']
Seoul.head()
Seoul.reset_index(inplace=True, drop=True)
Seoul.head()
AveSeoul = pd.pivot_table(Seoul, index=['SiGunGu'])
AveSeoul
plt.figure(figsize=(20,10))
sns.boxplot(x='SiGunGu', y="거래금액(만원)", data=Seoul)
plt.show()
plt.figure(figsize=(20,10))
sns.boxplot(x='SiGunGu', y="거래금액(만원)", data=Seoul)
sns.swarmplot(x='SiGunGu', y="거래금액(만원)", data=Seoul, color=".6")
plt.show()
import json
geo_seoul = json.load(open('data/seoul_municipalities_geo_simple.json', encoding='utf-8'))
geo_seoul.keys() # 딕셔너리의 key 정보
geo_seoul['features'][0]
geo_seoul['features'][0]['geometry']['coordinates'][0]
len(geo_seoul['features'][0]['geometry']['coordinates'][0])
len(geo_seoul['features'][1]['geometry']['coordinates'][0])
geo_seoul['features'][0]['id'], geo_seoul['features'][0]['properties']['name']
import folium
#folium.Map(location=[48.8667, 2.33333]) # 프랑스 파리
#folium.Map([48.8667, 2.33333]) # 프랑스 파리
#folium.Map(location=[37.56667, 126.97806]) # 대한민국 서울
#folium.Map(location=[37.56667, 126.97806], zoom_start=8) # default 10
#folium.Map(location=[37.56667, 126.97806], min_zoom=11, max_zoom=11) # 위치 고정
folium.Map(location=[37.5502, 126.982], min_zoom=11, max_zoom=11, tiles='Stamen Toner') # 서울시
map = folium.Map(location=[37.5502, 126.982], min_zoom=11, max_zoom=11,
tiles='Stamen Toner') # 서울시
map.choropleth(geo_data=geo_seoul,
data=AveSeoul['거래금액(만원)'],
columns=[AveSeoul.index, AveSeoul['거래금액(만원)']], # 주의!!
fill_color='Reds',
legend_name = '거래금액(만원)',
key_on='feature.id') # 가능
# key_on='feature.properties.name') # 가능
map
map.save('data/map/map_seoul.html')
# 지도 저장하기
map = folium.Map(location=[37.5502, 126.982], min_zoom=11, max_zoom=11, tiles='Stamen Toner') # 서울시
map.choropleth(geo_data=geo_seoul,
data=AveSeoul['연면적(㎡)'],
columns=[AveSeoul.index, AveSeoul['연면적(㎡)']], # 주의!!
fill_color='Blues',
legend_name = '연면적(㎡)',
# key_on='feature.id') # 가능
key_on='feature.properties.name') # 가능
map
map.save('data/map/map_seoul_area.html')
map = folium.Map(location=[37.5502, 126.982], min_zoom=11, max_zoom=11, tiles='Stamen Toner') # 서울시
map.choropleth(geo_data=geo_seoul,
data=AveSeoul['건축년도'],
columns=[AveSeoul.index, AveSeoul['건축년도']], # 주의!!
fill_color='Purples',
legend_name = '건축년도',
# key_on='feature.id') # 가능
key_on='feature.properties.name') # 가능
map
map.save('data/map/map_seoul_year.html')
map_pos = [37.56667, 126.97806] # 서울시
m = folium.Map(map_pos, min_zoom=11, max_zoom=11)
folium.CircleMarker(location = map_pos, radius = 200).add_to(m) # default는 blue
marker_pos = [37.506178, 127.049236] # 서울시 강남구 스땡벅스 선릉역점
folium.Marker(marker_pos).add_to(m) # default는 blue
m
map_pos = [37.56667, 126.97806] # 서울시
m = folium.Map(map_pos, min_zoom=11, max_zoom=11)
folium.CircleMarker(location = map_pos, radius = 200, color='blue', fill_color='blue').add_to(m)
marker_pos = [37.506178, 127.049236] # 서울시 강남구 스땡벅스 선릉역점
folium.Marker(marker_pos, popup='스땡벅스 선릉역점').add_to(m) # default는 blue
m
# radius의 의미 이해하기
map_pos = [37.56667, 126.97806] # 서울시
m = folium.Map(map_pos, min_zoom=11, max_zoom=11)
folium.CircleMarker(location = map_pos, radius = 200, color='blue', fill_color='blue').add_to(m)
folium.CircleMarker(location = map_pos, radius = 100, color='red', fill_color='red').add_to(m)
folium.Circle(location = map_pos, radius = 1000, color='black', fill_color='black').add_to(m) # 단위 : 미터
marker_pos = [37.506178, 127.049236] # 서울시 강남구 스타땡스 선릉역점
folium.Marker(marker_pos, popup='스타땡스 선릉역점').add_to(m)
# https://www.google.co.kr/maps
m
# radius의 의미 이해하기
map_pos = [37.56667, 126.97806] # 서울시
m = folium.Map(map_pos, min_zoom=10, max_zoom=10)
folium.CircleMarker(location = map_pos, radius = 200, color='blue',
fill_color='blue').add_to(m)
folium.CircleMarker(location = map_pos, radius = 100, color='red',
fill_color='red').add_to(m)
folium.Circle(location = map_pos, radius = 1000, color='black',
fill_color='black').add_to(m) # 단위 : 미터
marker_pos = [37.506178, 127.049236] # 서울시 강남구 스타땡스 선릉역점
folium.Marker(marker_pos, popup='스타땡스 선릉역점').add_to(m) # default는 blue
m
House1 = Seoul[Seoul['건축년도'] > 2017]
House2 = House1[House1['주택유형']=='단독']
House = House2[House2['거래금액(만원)']<100000] # 10억 미만
House
House.reset_index(inplace=True, drop=True)
House
marker_pos1 = [37.632145, 127.036528] # 강북구 번2동 번동중학교
marker_pos2 = [37.560220, 127.013759] # 중구 신당동 청구역
marker_pos3 = [37.608858, 127.001017] # 성북구 정릉동 고려대학교
marker_pos4 = [37.585363, 127.086666] # 중랑구 면목동 면동초등학교
target_pos = [37.610714, 127.021700] # 서울미아초등학교
# 서울특별시 성북구 길음1동 삼양로 77
m = folium.Map(target_pos, min_zoom=12, max_zoom=12)
folium.Circle(location = target_pos, radius = 5000,
color='red', fill_color='red').add_to(m) # 반경 5km
folium.CircleMarker(location = marker_pos1, radius = House['거래금액(만원)'][0]/5000,
color='blue', fill_color='blue').add_to(m)
folium.CircleMarker(location = marker_pos2, radius = House['거래금액(만원)'][1]/5000,
color='blue', fill_color='blue').add_to(m)
folium.CircleMarker(location = marker_pos3, radius = House['거래금액(만원)'][2]/5000,
color='blue', fill_color='blue').add_to(m)
folium.CircleMarker(location = marker_pos4, radius = House['거래금액(만원)'][3]/5000,
color='blue', fill_color='blue').add_to(m)
folium.Marker(target_pos, popup='서울 미아초등학교',
icon=folium.Icon(color='red')).add_to(m)
folium.Marker(marker_pos1, popup='집1').add_to(m)
folium.Marker(marker_pos2, popup='집2').add_to(m)
folium.Marker(marker_pos3, popup='집3').add_to(m)
folium.Marker(marker_pos4, popup='집4').add_to(m)
m
m.save('data/map/map_seoul_house.html')
geo_korea = json.load(open('data/skorea_municipalities_geo_simple.json', encoding='utf-8'))
geo_korea.keys()
geo_korea['features'][230] # 전국 지도
geo_seoul['features'][4] # 서울시 지도
geo_korea['features'][230]['id'], geo_korea['features'][230]['properties']['name']
geo_seoul['features'][4]['id'], geo_seoul['features'][4]['properties']['name']
AveSeoul.index
map = folium.Map(location=[37.5502, 126.982], zoom_start=11, tiles='Stamen Toner')
map.choropleth(geo_data=geo_korea,
data=AveSeoul['거래금액(만원)'],
columns=[AveSeoul.index, AveSeoul['거래금액(만원)']], # 주의!!
fill_color='Reds',
key_on='feature.properties.name') # 주의!!
# key_on='feature.id') # 표시되지 않음
map
map.save('data/map/map_seoul_korea.html')
df[df['SiGunGu'] == '중구']
# 중복 주의
Busan = df[df['SiDo'] == '부산광역시']
Busan.head()
Busan.reset_index(inplace=True, drop=True)
Busan.head()
Busan['SiGunGu'].unique()
Seoul['SiGunGu'].unique()
Busan['ID'].unique()
AveBusan = pd.pivot_table(Busan, index=['ID']) # ID를 index로.. (전국에 표시해야 하므로..)
AveBusan
plt.figure(figsize=(20,10))
sns.boxplot(x='ID', y="거래금액(만원)", data=Busan)
plt.show()
plt.figure(figsize=(20,10))
sns.boxplot(x='ID', y="거래금액(만원)", data=Busan)
sns.swarmplot(x='ID', y="거래금액(만원)", data=Busan, color=".6")
plt.show()
geo_korea['features'][220]
geo_korea['features'][220]['id'], geo_korea['features'][220]['properties']['name']
map = folium.Map(location=[35.17944, 129.07556], min_zoom=10, max_zoom=10,
tiles='Stamen Toner') # 부산광역시
map.choropleth(geo_data=geo_korea,
data=AveBusan['거래금액(만원)'],
columns=[AveBusan.index, AveBusan['거래금액(만원)']], # 주의!! DataFrame.index만 적용 가능함
fill_color='Greens',
legend_name = '거래금액(만원)',
key_on='feature.id')
# key_on='feature.properties.name') # 나타나지 않음
map
map.save('data/map/map_busan.html')
House1 = Busan[Busan['건축년도'] > 2000]
House2 = House1[House1['주택유형']=='다가구']
House = House2[House2['거래금액(만원)']<50000]
House
House.reset_index(inplace=True, drop=True)
House
marker_pos = [
[35.114992, 129.082752], # 남구 감만동 동항초등학교
[35.228946, 129.157009], # 해운대구 반송동 송운초등학교
[35.196538, 129.008752], # 북구 구포동 포천초등학교
[35.170736, 129.115990], # 수영구 수영동 주민센터
[35.069483, 128.979623], # 사하구 다대동 다송초등학교
[35.233308, 129.147999], # 해운대구 반송동 동부산대학교
[35.214680, 129.011909], # 북구 덕천동 덕천중학교
[35.121655, 129.036808], # 동구 동구 초량동 부산고등학교
[35.098581, 129.015987]] # 서구 아미동 아미초등학교
marker_pos
target_pos = [35.220730, 129.104888] # 금정구 서곡초등학교
baseball_pos = [35.195578, 129.061319] # 동래구 사직 야구장
m = folium.Map(target_pos, min_zoom=11, max_zoom=11)
folium.Circle(location = target_pos, radius = 6000, color='red', fill_color='red').add_to(m) # 반경 6km
folium.Circle(location = baseball_pos, radius = 6000, color='yellow', fill_color='black').add_to(m) # 반경 6km
for n in range(len(marker_pos)):
folium.CircleMarker(location = marker_pos[n],
radius = House['거래금액(만원)'][n]/3000,
color='blue', fill_color='blue').add_to(m)
folium.Marker(target_pos, popup='서곡초등학교', icon=folium.Icon(color='red')).add_to(m)
folium.Marker(baseball_pos, popup='야구장', icon=folium.Icon(color='black')).add_to(m)
folium.Marker(marker_pos[0], popup='1번 집').add_to(m)
folium.Marker(marker_pos[1], popup='2번 집').add_to(m)
folium.Marker(marker_pos[2], popup='3번 집').add_to(m)
folium.Marker(marker_pos[3], popup='4번 집').add_to(m)
folium.Marker(marker_pos[4], popup='5번 집').add_to(m)
folium.Marker(marker_pos[5], popup='6번 집').add_to(m)
folium.Marker(marker_pos[6], popup='7번 집').add_to(m)
folium.Marker(marker_pos[7], popup='8번 집').add_to(m)
folium.Marker(marker_pos[8], popup='9번 집').add_to(m)
m
m.save('data/map/map_busan_house.html')
AveBusan0 = pd.pivot_table(Busan, index=['SiGunGu'])
AveBusan0
geo_korea['features'][220]['id'], geo_korea['features'][220]['properties']['name']
map = folium.Map(location=[35.17944, 129.07556], min_zoom=11, max_zoom=11, tiles='Stamen Toner') # 부산광역시
map.choropleth(geo_data=geo_korea,
data=AveBusan0['거래금액(만원)'],
columns=[AveBusan0.index, AveBusan0['거래금액(만원)']],
fill_color='Greens',
key_on='feature.properties.name')
map # 흰색과 검정색 영역의 의미?
map = folium.Map(location=[35.17944, 129.07556], min_zoom=7, max_zoom=7, tiles='Stamen Toner') # 부산광역시
map.choropleth(geo_data=geo_korea,
data=AveBusan0['거래금액(만원)'],
columns=[AveBusan0.index, AveBusan0['거래금액(만원)']],
fill_color='Greens',
legend_name = '거래금액(만원)',
key_on='feature.properties.name')
map # 흰색과 검정색 영역의 의미?
map.save('data/map/map_busan_korea_error.html')
AveKorea = pd.pivot_table(df, index=['ID'])
AveKorea
AveKorea[AveKorea.index == '고성']
#map = folium.Map(location=[36.775356, 127.802357], min_zoom=7, max_zoom=7,
# tiles='Stamen Toner') # 충청북도 괴산군 문광면
map = folium.Map(location=[36.775356, 127.802357], zoom_start=7,
tiles='Stamen Toner') # 충청북도 괴산군 문광면
map.choropleth(geo_data=geo_korea,
data=AveKorea['거래금액(만원)'],
columns=[AveKorea.index, AveKorea['거래금액(만원)']], # 주의!!
fill_color='YlGnBu',
legend_name = '거래금액(만원)',
# key_on='feature.properties.name') # 주의!!
key_on='feature.id') # 표시되지 않음
map
# (예) 검정색 영역 중 '고성' ---> json 파일에서 고성(경남), 고성(강원)
# 과제 : 오류 수정!!!
map.save('data/map/map_korea.html')
geo_korea_id = []
for k_id in geo_korea['features']:
geo_korea_id.append(k_id['id'])
geo_korea_id = pd.DataFrame(geo_korea_id, columns=['ID'])
geo_korea_id.head()
AveKorea.index
set(geo_korea_id['ID'].unique()) - set(AveKorea.index.unique())
set(AveKorea.index.unique()) - set(geo_korea_id['ID'].unique())
This module contains the following sets of palettes:
marker_pos0 = [
[35.114992, 129.082752, '1번: 비싸지만 넓고 최근에 지은 집'], # 남구 감만동 동항초등학교
[35.228946, 129.157009, '2번: 적절한 면적과 가격의 집'], # 해운대구 반송동 송운초등학교
[35.196538, 129.008752, '3번: 좁은데 저렴하지도 않고 오래된 집ㅜ_ㅜ;'], # 북구 구포동 포천초등학교
[35.170736, 129.115990, '4번: 비싸지만 새로 지은 집'], # 수영구 수영동 주민센터
[35.069483, 128.979623, '5번: 적당한 크기에 조금 오래된 다소 비싼 집'], # 사하구 다대동 다송초등학교
[35.233308, 129.147999, '6번: 오래 되었지만 적당한 크기의 싼 집'], # 해운대구 반송동 동부산대학교
[35.214680, 129.011909, '7번: 넓지만 오래되었고 비싼 집'], # 북구 덕천동 덕천중학교
[35.121655, 129.036808, '8번: 오래 되었지만 적절한 가격의 집'], # 동구 동구 초량동 부산고등학교
[35.098581, 129.015987, '9번: 좁지만 최근에 지었고 싼 집']] # 서구 아미동 아미초등학교
marker_pos0
marker_posA = pd.DataFrame(marker_pos0, columns = ["위도", "경도", "집 정보"])
marker_posA
marker_posA.to_excel('data/house_sample.xlsx',index=None, encoding='utf-8') # 파일 저장
marker_posB = pd.read_excel("data/house_sample.xlsx")
marker_posB
[marker_posB['위도'][0], marker_posB['경도'][0], marker_posB['집 정보'][0]]
target_pos = [35.220730, 129.104888] # 금정구 서곡초등학교
baseball_pos = [35.195578, 129.061319] # 동래구 사직 야구장
m = folium.Map(target_pos, min_zoom=11, max_zoom=11)
folium.Circle(location = target_pos, radius = 6000, color='red', fill_color='red').add_to(m)
folium.Circle(location = baseball_pos, radius = 6000, color='yellow', fill_color='black').add_to(m)
for n in range(len(marker_posB)):
folium.CircleMarker(location = [marker_posB['위도'][n], marker_posB['경도'][n]],
radius = House['거래금액(만원)'][n]/3000, color='blue', fill_color='blue').add_to(m)
folium.Marker([marker_posB['위도'][n], marker_posB['경도'][n]], popup=marker_posB['집 정보'][n]).add_to(m)
folium.Marker(target_pos, popup='서곡초등학교', icon=folium.Icon(color='red')).add_to(m)
folium.Marker(baseball_pos, popup='야구장', icon=folium.Icon(color='black')).add_to(m)
m
m.save('data/map/map_busan_house_info.html')
kb_chicken = pd.read_excel("data/kb_chicken.xlsx")
kb_chicken # 웹 크롤링을 활용하여 자동으로 가져올 수 있음
import googlemaps
gmap_key = "********************************" # 각자의 Google Maps API 용 Key 입력
gmaps = googlemaps.Client(key=gmap_key)
gmaps.geocode(str(kb_chicken['주소'][0]))[0]
gmaps.geocode(str(kb_chicken['주소'][0]))[0]['geometry']
gmaps.geocode(str(kb_chicken['주소'][0]))[0]['geometry']['location']
lat = []
lng = []
for n in range(len(kb_chicken)):
lat.append(gmaps.geocode(str(kb_chicken['주소'][n]))[0]['geometry']['location']['lat'])
lng.append(gmaps.geocode(str(kb_chicken['주소'][n]))[0]['geometry']['location']['lng'])
kb_chicken['lat'] = lat
kb_chicken['lng'] = lng
kb_chicken
target_pos = [37.291934, 127.017168] # KB인재니움; 경기도 수원시 장안구 영화동 171-1
m = folium.Map(target_pos, min_zoom=15, max_zoom=15)
folium.Circle(location = target_pos, radius = 700, color='red', fill_color='red').add_to(m)
for n in range(len(kb_chicken)):
folium.CircleMarker(location = [kb_chicken['lat'][n], kb_chicken['lng'][n]],
radius = kb_chicken['가격'][n]/500, color='blue', fill_color='blue').add_to(m)
folium.Marker([kb_chicken['lat'][n], kb_chicken['lng'][n]],
popup=kb_chicken['상호'][n]+', '+str(kb_chicken['가격'][n])+'원, '+'평점: '+str(kb_chicken['평점'][n]),
icon=folium.Icon(color='blue')).add_to(m)
folium.Marker(target_pos, popup='KB인재니움', icon=folium.Icon(color='red')).add_to(m)
m
m.save('data/map/kb_chicken.html')